import { ref, reactive, onMounted, } from "vue";
import { type PaginationProps } from "@pureadmin/table";
import { useRoute } from "vue-router";
import qs from "qs";
import { ElMessage, FormInstance } from "element-plus";
import { emitter } from "@/utils/mitt";
import Sortable from 'sortablejs'
import { vLoading } from "element-plus";
import {
  GetInfoByAcrmId,
  FinancingApprovalQuotaGetAllFinancingAlgorithmByPagedAndSort,
  AlgorithmSaveResultGetAllNamesOptions,
  AlgorithmicCreditEvaluationModelAlgorithmAnalysis,
  EvaluationAlgorithmResultGetInfo,
  CreateQuotaAssessmentModel,
  GetQuotaUserExtise,
  GetAccountsReceivableAmountFinancingApproval,
  FinancingApprovalQuotaDelete
} from "@/api/stu/SupplyChainFinance";
export function useFincialCredit() {
  const dataList = ref();
  const route = useRoute()
  const RefStubimAddFrom = ref();
  const loading = ref<boolean>(false);
  const tLoding = ref<boolean>(false)
  const selectData = ref() //选中当前行的数据
  const algorOptionist = ref([]) //算法选择的数据
  const saveParams = ref() //测算的参数
  const detailData = ref('')//算法详情数据
  const listComeData = ref('')//保存后查看
  const showType = ref()
  const dialogVisible = ref(false)
  const formData = reactive({
    supName: '',
    acrmId: '',
    selectParams: '',
    modelName: '',
    numberOfDelays: '',
    numberOfTradeDefaults: '',
    numberOfReturns: '',
    transactionFlow: '',
    numberOfQualifiedGoods: '',
    deliveryCycle: '',
    arrivalCycle: '',
    totalTransactionAmount: '',
    productNegativeRating: '',
    numberOfCustomerComplaints: '',
    accountsReceivableAmount: '',
    financingAmount: '',
    tempScore: '',
  })
  const selectAcrmId = ref('')
  const isNeedData = ref(false) //一张订单需要核定一次 但是供应商数据只需要填写一次 判断该订单下的供应商是否需要填写自定义数据
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    pageSizes: [5, 10, 15],
    background: true
  });
  const pagination2 = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    pageSizes: [5, 10, 15],
    background: true
  });

  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      fixed: "left",
      minWidth: 50
    },
    {
      label: "企业名称",
      prop: "supplyName",
    },
    {
      label: "采购项目",
      prop: "projectAccountsReceivableName",
    },
    {
      label: "额度核定算法模型",
      prop: "quotaAssessmentModelName",
    },
    {
      label: "预测结果集结果Y",
      prop: "yPredTrain",
    },
    {
      label: "核定结果",
      prop: "isMeasure",
      fixed: "right",
      width: 100,
      cellRenderer: ({ row }) => (
        <el-tag type={
          row.isMeasure ? "success" : "danger"}>
          {
            row.isMeasure ? "已完成" : '未完成'
          }
        </el-tag>
      )
    },
    {
      label: "操作",
      fixed: "right",
      width: 200,
      slot: "operation"
    }
  ];

  const rules: any = {
    numberOfDelays: [
      {
        required: true, type: 'number',
        validator: (rule: any, value: number, callback: () => void) => {
          if (typeof value == 'string' || value < 0 || value > 1000000) {
            return callback(new Error('延期次数范围为0-1000000'))
          } else {
            return callback();
          }
        },
        trigger: 'blur'
      }
    ], numberOfTradeDefaults: [
      {
        required: true, type: 'number',
        validator: (rule: any, value: number, callback: () => void) => {
          if (typeof value == 'string' || value < 0 || value > 1000000) {
            return callback(new Error('交易违约次数范围为0-1000000'))
          } else {
            return callback();
          }
        },
        trigger: 'blur'
      }
    ], numberOfReturns: [
      {
        required: true, type: 'number',
        validator: (rule: any, value: number, callback: () => void) => {
          if (typeof value == 'string' || value < 0 || value > 1000000) {
            return callback(new Error('退货次数范围为0-1000000'))
          } else {
            return callback();
          }
        },
        trigger: 'blur'
      }
    ], transactionFlow: [
      {
        required: true, type: 'number',
        validator: (rule: any, value: number, callback: () => void) => {
          if (typeof value == 'string' || value > 1000000000000 || value < 0) {
            return callback(new Error('交易流水范围：0-1万亿'))
          } else {
            return callback();
          }
        },
        trigger: 'blur'
      }
    ], numberOfQualifiedGoods: [
      {
        required: true, type: 'number',
        validator: (rule: any, value: number, callback: () => void) => {
          if (typeof value == 'string' || value < 0 || value > 1000000) {
            return callback(new Error('商品合格次数范围为0-1000000'))
          } else {
            return callback();
          }
        },
        trigger: 'blur'
      }
    ], deliveryCycle: [
      {
        required: true, type: 'number',
        validator: (rule: any, value: number, callback: () => void) => {
          if (typeof value == 'string' || value < 0 || value > 1000000) {
            return callback(new Error('发货周期范围为0-1000000'))
          } else {
            return callback();
          }
        },
        trigger: 'blur'
      }
    ], arrivalCycle: [
      {
        required: true, type: 'number',
        validator: (rule: any, value: number, callback: () => void) => {
          if (typeof value == 'string' || value < 0 || value > 1000000) {
            return callback(new Error('到货周期范围为0-1000000'))
          } else {
            return callback();
          }
        },
        trigger: 'blur'
      }
    ], totalTransactionAmount: [
      {
        required: true, type: 'number',
        validator: (rule: any, value: number, callback: () => void) => {
          if (typeof value == 'string' || value > 1000000000000 || value < 0) {
            return callback(new Error('总成交金额范围：0-1万亿'))
          } else {
            return callback();
          }
        },
        trigger: 'blur'
      }
    ],
    productNegativeRating: [
      {
        required: true, type: 'number',
        validator: (rule: any, value: number, callback: () => void) => {
          if (typeof value == 'string' || value > 100 || value < 0) {
            return callback(new Error('商品差评率范围：0-100'))
          } else {
            return callback();
          }
        },
        trigger: 'blur'
      }
    ], numberOfCustomerComplaints: [
      {
        required: true, type: 'number',
        validator: (rule: any, value: number, callback: () => void) => {
          if (typeof value == 'string' || value < 0 || value > 1000000) {
            return callback(new Error('客户投诉次数范围：0-1000000'))
          } else {
            return callback();
          }
        },
        trigger: 'blur'
      }
    ],
    financingAmount: [
      {
        required: true, type: 'number',
        validator: (rule: any, value: number, callback: () => void) => {
          if (typeof value == 'string' || value > 1000000000000 || value < 0) {
            return callback(new Error('融资额度范围：0-1万亿'))
          } else {
            return callback();
          }
        },
        trigger: 'blur'
      }
    ],
    accountsReceivableAmount: [
      {
        required: true, type: 'number',
        validator: (rule: any, value: number, callback: () => void) => {
          if (typeof value == 'string' || value > 1000000000000 || value < 0) {
            return callback(new Error('应收账款范围：0-1万亿'))
          } else {
            return callback();
          }
        },
        trigger: 'blur'
      }
    ],
  }
  const handleCurrentChange = val => {
    getList()
  };
  function handleSizeChange() {
    getList()
  }

  //获取任务列表
  async function getList() {
    const res = await FinancingApprovalQuotaGetAllFinancingAlgorithmByPagedAndSort({
      taskId: route.query.taskId,
      planId: route.query.planId,
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize
    });
    if (res.success) {
      res.data.items.forEach((item) => {
        item.projectAccountsReceivableName = item.projectAccountsReceivableName.split(";").join(",").replace(/^,/, "");
      })
      dataList.value = res.data.items;
      loading.value = false;
      pagination.total = res.data.totalCount;
    } else {
      ElMessage.error(res.msg);
      setTimeout(() => { loading.value = false; }, 1500)
    }
  }

  //查看模型详情
  async function newGrade(row) {
    selectData.value = row
    formData.supName = row.supplyName
    // let res = await GetQuotaUserExtise(qs.stringify({ seiId: selectData.value.seiId }))
    // if (!res.success) {
    Object.keys(formData).forEach(key => {
      if (key !== 'supName') {
        formData[key] = '';
      }
    });
    // isNeedData.value = false
    let res1 = await GetAccountsReceivableAmountFinancingApproval(qs.stringify({ projectAccountsReceivable: selectData.value.projectAccountsReceivable }))
    if (res1.success) {
      formData.financingAmount = res1.data
      formData.accountsReceivableAmount = res1.data
    } else {
      ElMessage.error(res1.msg)
    }
    // } else {
    //   formData.numberOfDelays = res.data.numberOfDelays
    //   formData.numberOfTradeDefaults = res.data.numberOfTradeDefaults
    //   formData.numberOfReturns = res.data.numberOfReturns
    //   formData.transactionFlow = res.data.transactionFlow
    //   formData.numberOfQualifiedGoods = res.data.numberOfQualifiedGoods
    //   formData.deliveryCycle = res.data.deliveryCycle
    //   formData.arrivalCycle = res.data.arrivalCycle
    //   formData.totalTransactionAmount = res.data.totalTransactionAmount
    //   formData.productNegativeRating = res.data.productNegativeRating
    //   formData.numberOfCustomerComplaints = res.data.numberOfCustomerComplaints
    //   formData.financingAmount = res.data.financingAmount
    //   formData.accountsReceivableAmount = res.data.accountsReceivableAmount
    //   isNeedData.value = true
    // }
    dialogVisible.value = true
  }

  async function changeAlgro() {
    selectAcrmId.value = formData.acrmId
    formData.modelName = algorOptionist.value.find(item => item.algorithmResultId == formData.acrmId).algorithmModelName
    let data = qs.stringify({
      acrmId: formData.acrmId,
      isCalculate: true
    })
    let res = await GetInfoByAcrmId(data)
    if (res.success) {
      res.data.indexSelection = JSON.parse(res.data.indexSelection)
      res.data.indexSelection.pop()
      saveParams.value = res.data
      formData.selectParams = res.data.indexSelection.map(item => item.Value).join(",");
    } else {
      ElMessage.error(res.msg)
    }
  }
  function CloseEntryPlatform(row: FormInstance | undefined) {
    console.log(row);
    formData.supName = '',
      formData.acrmId = '',
      formData.selectParams = '',
      row.resetFields()
    dialogVisible.value = false
  }
  async function saveCredit(row: FormInstance | undefined) {
    if (!formData.acrmId) {
      ElMessage.warning('请选择额度核定模型')
      return
    }
    (row as any).validate(async valid => {
      if (!valid) return;
      // if (isNeedData.value) {
      //   const algorithmType = saveParams.value.type
      //   let data = {
      //     querySqlString: saveParams.value.indexSelection.map(item => item.Key).join(',') + ',financingAmount',
      //     columnName: saveParams.value.indexSelection.map(item => item.Key).join(';') + ';financingAmount',
      //     selectdy: "financingAmount",
      //     algorithmTypeEnum: saveParams.value.type,
      //     modelType: 2,
      //     isApprovedMeasurement: true,
      //     sEIId: selectData.value.seiId,
      //     updateCreditRating: "",
      //     updateQuotaAssessment: {
      //       seiId: "",
      //       financingApprovalId: selectData.value.financingApprovalId,
      //       quotaAssessmentModelName: formData.modelName,
      //       quotaAssessmentModel: {
      //         seiId: '',
      //         numberOfDelays: formData.numberOfDelays,
      //         numberOfTradeDefaults: formData.numberOfTradeDefaults,
      //         numberOfReturns: formData.numberOfReturns,
      //         transactionFlow: formData.transactionFlow,
      //         quotaAssessmentModelId: "",
      //         numberOfQualifiedGoods: formData.numberOfQualifiedGoods,
      //         deliveryCycle: formData.deliveryCycle,
      //         arrivalCycle: formData.arrivalCycle,
      //         totalTransactionAmount: formData.totalTransactionAmount,
      //         productNegativeRating: formData.productNegativeRating,
      //         numberOfCustomerComplaints: formData.numberOfCustomerComplaints,
      //         accountsReceivableAmount: formData.accountsReceivableAmount,
      //         financingAmount: formData.financingAmount,
      //         tempScore: '',
      //       }
      //     },
      //     algorithmParameters: '',
      //     neuralNetworkParameters: '',
      //   }
      //   if (algorithmType == "4") {
      //     data.xgBoostConfig = JSON.parse(saveParams.value.modelParameterSetting)
      //   }
      //   if (algorithmType == "5") {
      //     console.log(2222);

      //     data.decisionTreeRegressionConfig = JSON.parse(saveParams.value.modelParameterSetting)
      //   }
      //   if (algorithmType == "6") {
      //     data.knnConfig = JSON.parse(saveParams.value.modelParameterSetting)
      //   }
      //   if (algorithmType == "7") {
      //     data.randomForestRegressionConfig = JSON.parse(saveParams.value.modelParameterSetting)
      //   }
      //   let res = await AlgorithmicCreditEvaluationModelAlgorithmAnalysis(data)
      //   if (res.success) {
      //     detailData.value = res.data
      //     dialogVisible.value = false
      //     cancelCreat()
      //     tLoding.value = true
      //     showType.value = saveParams.value.type == '4' ? 'XGBoost回归' : saveParams.value.type == '5' ? '决策树回归' : saveParams.value.type == '6' ? 'K近邻（KNN）回归' : '随机森林回归'
      //     ElMessage.success(res.msg)
      //   } else {
      //     ElMessage.error(res.msg)
      //   }
      // } else {
      let addData = {
        numberOfDelays: formData.numberOfDelays,
        numberOfTradeDefaults: formData.numberOfTradeDefaults,
        numberOfReturns: formData.numberOfReturns,
        transactionFlow: formData.transactionFlow,
        numberOfQualifiedGoods: formData.numberOfQualifiedGoods,
        deliveryCycle: formData.deliveryCycle,
        arrivalCycle: formData.arrivalCycle,
        totalTransactionAmount: formData.totalTransactionAmount,
        productNegativeRating: formData.productNegativeRating,
        numberOfCustomerComplaints: formData.numberOfCustomerComplaints,
        financingAmount: formData.financingAmount,
        SEIId: selectData.value.seiId,
        projectAccountsReceivable: selectData.value.projectAccountsReceivable,
        accountsReceivableAmount: formData.accountsReceivableAmount,
        financingApprovalId: selectData.value.financingApprovalId
      }
      let res = await CreateQuotaAssessmentModel(addData)
      if (res.success) {
        const algorithmType = saveParams.value.type
        let data = {
          querySqlString: saveParams.value.indexSelection.map(item => item.Key).join(',') + ',financingAmount',
          columnName: saveParams.value.indexSelection.map(item => item.Key).join(';') + ';financingAmount',
          selectdy: "financingAmount",
          algorithmTypeEnum: saveParams.value.type,
          modelType: 2,
          isApprovedMeasurement: true,
          sEIId: selectData.value.seiId,
          financingApprovalId: selectData.value.financingApprovalId,
          updateCreditRating: "",
          updateQuotaAssessment: {
            seiId: "",
            financingApprovalId: selectData.value.financingApprovalId,
            quotaAssessmentModelName: formData.modelName,
            quotaAssessmentModel: {
              seiId: '',
              financingApprovalId: selectData.value.financingApprovalId,
              numberOfDelays: formData.numberOfDelays,
              numberOfTradeDefaults: formData.numberOfTradeDefaults,
              numberOfReturns: formData.numberOfReturns,
              transactionFlow: formData.transactionFlow,
              quotaAssessmentModelId: "",
              numberOfQualifiedGoods: formData.numberOfQualifiedGoods,
              deliveryCycle: formData.deliveryCycle,
              arrivalCycle: formData.arrivalCycle,
              totalTransactionAmount: formData.totalTransactionAmount,
              productNegativeRating: formData.productNegativeRating,
              numberOfCustomerComplaints: formData.numberOfCustomerComplaints,
              accountsReceivableAmount: formData.accountsReceivableAmount,
              financingAmount: formData.financingAmount,
              tempScore: '',
            }
          },
          algorithmParameters: '',
          neuralNetworkParameters: '',
        }
        if (algorithmType == "4") {
          data.xgBoostConfig = JSON.parse(saveParams.value.modelParameterSetting)
        }
        if (algorithmType == "5") {
          data.decisionTreeRegressionConfig = JSON.parse(saveParams.value.modelParameterSetting)
        }
        if (algorithmType == "6") {
          data.knnConfig = JSON.parse(saveParams.value.modelParameterSetting)
        }
        if (algorithmType == "7") {
          data.randomForestRegressionConfig = JSON.parse(saveParams.value.modelParameterSetting)
        }
        let res = await AlgorithmicCreditEvaluationModelAlgorithmAnalysis(data)
        if (res.success) {
          detailData.value = res.data
          dialogVisible.value = false
          tLoding.value = true
          showType.value = saveParams.value.type == '4' ? 'XGBoost回归' : saveParams.value.type == '5' ? '决策树回归' : saveParams.value.type == '6' ? 'K近邻（KNN）回归' : '随机森林回归'
          ElMessage.success(res.msg)
        } else {
          ElMessage.error(res.msg)
        }
      } else {
        ElMessage.error(res.msg)
      }
    })
  }


  async function checkPor(row) {
    const data = qs.stringify({
      financingApprovalId: row.financingApprovalId,
      type: 2,
    })
    let res = await EvaluationAlgorithmResultGetInfo(data)
    if (res.success) {
      listComeData.value = JSON.parse(res.data.algorithmCalculateResult)
      showType.value = listComeData.value.type
      tLoding.value = true
    } else {
      ElMessage.error(res.msg)
    }
  }

  onMounted(async () => {
    getList()
    const data = qs.stringify({
      modelType: 2,
      planId: route.query.planId,
      taskId: route.query.taskId
    })
    let res = await AlgorithmSaveResultGetAllNamesOptions(data)
    if (res.success) {
      algorOptionist.value = res.data
    } else {
      ElMessage.error(res.msg)
    }
  })

  emitter.on("saveNewApprovalResult", () => {
    console.log(selectData.value.financingApprovalId);

    const data = qs.stringify({ id: selectData.value.financingApprovalId })
    let res = FinancingApprovalQuotaDelete(data)
    if (res) {
      tLoding.value = false
      formData.acrmId = ''
      formData.selectParams = ''
      listComeData.value = ''
      Object.keys(formData).forEach(key => {
        if (key !== 'supName') {
          formData[key] = '';
        }
      });
      getList()
    } else {
      ElMessage.error('删除额度核定数据失败')
    }

  })

  emitter.on("closeNewApprovalResult", () => {
    tLoding.value = false
    formData.acrmId = ''
    formData.selectParams = ''
    listComeData.value = ''
    Object.keys(formData).forEach(key => {
      if (key !== 'supName') {
        formData[key] = '';
      }
    });
    getList()
  })
  //取整
  function restrictPositiveIntegers(key) {
    formData[key] = Math.floor(formData[key])
  }
  return {
    columns,
    rules,
    loading,
    dataList,
    pagination,
    dialogVisible,
    tLoding,
    handleSizeChange,
    handleCurrentChange,
    checkPor,
    newGrade,
    detailData,
    formData,
    algorOptionist,
    changeAlgro,
    saveCredit,
    showType,
    saveParams,
    selectData,
    listComeData,
    RefStubimAddFrom,
    CloseEntryPlatform,
    isNeedData,
    selectAcrmId,
    restrictPositiveIntegers
  }
}